#include <mysql/mysql.h>
#include "server.h"
/*
int workServer(int netfd){
    MYSQL* mysql=mysql_init(NULL);
    MYSQL* ret=mysql_real_connect(
                                  mysql,
                                  "localhost",
                                  "root",
                                  "123",
                                  "test",
                                  0,NULL,0
                                 );
    if(ret==NULL){
        fprintf(stderr,"mysql_real_connect:%s\n",mysql_error(mysql));
        return -1;
    }
    char* path="/abc";
    lsServer(netfd,path,mysql);
    mysql_close(mysql);
    return 0;
}
*/
int lsServer(int netfd,char* path,MYSQL* mysql){
    char sql[1024]={0};
    printf("ls path=%s\n",path);
    sprintf(sql,"%s'%s';","select id from file where type = 'd' and path=",path);
    printf("sql=%s\n",sql);
    int qret=mysql_query(mysql,sql);
    printf("%d\n",qret);
    if(qret !=0){
        fprintf(stderr,"masql_query error:%s",mysql_error(mysql));
        return 0;
    }
    MYSQL_RES* res=mysql_store_result(mysql);
    printf("rows=%ld,clos=%d\n",mysql_num_rows(res),mysql_num_fields(res));
    MYSQL_ROW row=mysql_fetch_row(res);
    int rows=mysql_num_rows(res);
    if(rows==0){
        printf("错误路径\n");
        return 0;
    }
    printf("%s\n",row[0]);
    char id[1024] = {0};//id的字符串
    strcpy(id,row[0]);
    int id_num=atoi(id);
    printf("id=%d\n",id_num);

    char sql2[1024]={0};
    sprintf(sql2,"%s%s","select filename from file where tomb=0 and pre_id = ",id);
    printf("sql2=%s\n",sql2);

    int qret2=mysql_query(mysql,sql2);
    printf("%d\n",qret2);
    
    if(qret2 !=0){
        fprintf(stderr,"masql_query error:%s",mysql_error(mysql));
        return 0;
    }

    char resultArr[1024]={0};
    char buf[1024]={0};
    MYSQL_RES* res2=mysql_store_result(mysql);
    printf("rows=%ld,clos=%d\n",mysql_num_rows(res2),mysql_num_fields(res2));
    rows=mysql_num_rows(res2);
    
    MYSQL_ROW row2;
    if(rows==0){
        printf("空文件夹\n");
        return 0;
    }
    while((row2=mysql_fetch_row(res2))!=NULL){
        for(unsigned int j=0;j<mysql_num_fields(res2);j++){
            printf("%s\t",row2[j]);
            sprintf(resultArr,"%s%s"," ",row2[j]);
            strcat(buf,resultArr);
        }
        printf("\n");
    }
    printf("resultArr=%s\n",resultArr);
    printf("buf=%s\n",buf);

    train_t train;
    bzero(&train,sizeof(train));
    train.dataLength=strlen(buf);
    strcpy(train.data,buf);
    printf("train length=%d\n",train.dataLength);
    printf("train data=%s\n",train.data);
    int ret=send(netfd,&train,sizeof(int)+train.dataLength,MSG_NOSIGNAL);
    ERROR_CHECK(ret,-1,"ls send");
    printf("send ret=%d\n",ret);
    bzero(buf,sizeof(buf));
    bzero(resultArr,sizeof(resultArr));
    bzero(&train,sizeof(train));
    return 0;
}
